package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.PrivacyVideoAdapter;
import flc.ast.adapter.VideoAdapter;
import flc.ast.databinding.ActivityPrivacyVideoBinding;
import flc.ast.dialog.AddVideoDialog;
import flc.ast.dialog.EditDialog;
import flc.ast.dialog.InfoDialog;
import flc.ast.dialog.PrivacyVideoEditDialog;
import flc.ast.dialog.VideoEditDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class PrivacyVideoActivity extends BaseAc<ActivityPrivacyVideoBinding> {

    private PrivacyVideoAdapter videoAdapter;
    private List<String> listShow = new ArrayList<>();
    private BasePopupView editPopup;
    private int selPosition;
    private Dialog myDeleteDialog, myRenameDialog;
    private EditText dialogRename;
    private AddVideoDialog addVideoDialog;

    @Override
    protected int onCreate() {
        return R.layout.activity_privacy_video;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivPrivacyVideoBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivPrivacyVideoAdd.setOnClickListener(this);

        mDataBinding.rvVideoList.setLayoutManager(new GridLayoutManager(mContext, 2));
        videoAdapter = new PrivacyVideoAdapter();
        mDataBinding.rvVideoList.setAdapter(videoAdapter);
        videoAdapter.addChildClickViewIds(R.id.ivVideoItemEdit);
        videoAdapter.setOnItemClickListener(this);
        videoAdapter.setOnItemChildClickListener(this);

        //删除弹框
        deleteDialog();
        //重命名弹框
        renameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPrivacyVideoAdd://添加视频
                getPermission();
                break;
            //删除弹框
            case R.id.tvDialogDeleteConfirm://确定
                myDeleteDialog.dismiss();
                delete();
                break;
            case R.id.tvDialogDeleteCancel://取消
                myDeleteDialog.dismiss();
                break;
            //重命名弹框
            case R.id.tvDialogRenameConfirm://确定
                myRenameDialog.dismiss();
                String name = dialogRename.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(R.string.please_input_video_name);
                    return;
                }
                myRenameDialog.dismiss();
                FileUtils.rename(listShow.get(selPosition), name + "." + FileUtils.getFileExtension(listShow.get(selPosition)));
                getData();
                break;
            case R.id.tvDialogRenameCancel://取消
                myRenameDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        PlayLandscapeActivity.videoPath = videoAdapter.getItem(position);
        startActivity(PlayLandscapeActivity.class);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivVideoItemEdit://编辑
                selPosition = position;
                editDialog(view);
                break;
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_video_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        showAddVideoDialog();
                    }
                }).request();
    }

    private void getData() {
        listShow.clear();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myPrivacy;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                listShow.add(file.getPath());
            }
        }
        if (listShow.size() > 0) {
            videoAdapter.setList(listShow);
            mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
            mDataBinding.tvVideoNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvVideoList.setVisibility(View.GONE);
            mDataBinding.tvVideoNoData.setVisibility(View.VISIBLE);
        }
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //从此文件夹删除
                        FileUtils.delete(listShow.get(selPosition));
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    private void editDialog(View view) {
        PrivacyVideoEditDialog videoEditDialog = new PrivacyVideoEditDialog(mContext);
        editPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(view).hasShadowBg(false) // 去掉半透明背景
                .asCustom(videoEditDialog);
        videoEditDialog.setListener(new PrivacyVideoEditDialog.Ilistener() {
            @Override
            public void clickDelete() {
                myDeleteDialog.show();
            }

            @Override
            public void clickShare() {
                IntentUtil.shareVideo(mContext, listShow.get(selPosition));
            }

            @Override
            public void clickRename() {
                dialogRename.setText(FileUtils.getFileNameNoExtension(listShow.get(selPosition)));
                myRenameDialog.show();
            }

            @Override
            public void clickAddFolder() {
                delete();
            }

            @Override
            public void clickInfo() {
                showInfoDialog();
            }
        });
        editPopup.show();
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogDeleteConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogDeleteCancel);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        tip.setText(getString(R.string.is_delete_video));
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogRenameConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogRenameCancel);
        TextView title = inflate.findViewById(R.id.tvDialogRenameTitle);
        title.setText(getString(R.string.edit_video_name));
        dialogRename = inflate.findViewById(R.id.etDialogRenameText);
        dialogRename.setHint(getString(R.string.input_video_name));
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    private void showInfoDialog() {
        InfoDialog dialog = new InfoDialog(mContext);
        dialog.videoPath = listShow.get(selPosition);
        dialog.show();
    }

    private void showAddVideoDialog() {
        if (addVideoDialog == null) {
            addVideoDialog = new AddVideoDialog(mContext);
        }
        addVideoDialog.setListener(new AddVideoDialog.Listener() {
            @Override
            public void clickAdd(List<String> list) {
                for (String path : list) {
                    String filePath = FileUtil.generateFilePath(Content.myPrivacy, "." + FileUtils.getFileExtension(path));
                    FileUtils.copy(path, filePath);
                }
                getData();
                ToastUtils.showShort(getString(R.string.add_suc));
            }
        });
        addVideoDialog.show();
    }

}